package jh.activity;

import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.jh.ios.forecast.R;

import org.apache.cordova.MainApplication;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import constans.P;
import jh.adapter.CommunityAdapter;
import jh.interfaces.OnItemPictureClickListener;
import jh.model.CModel;
import jh.model.UserModel;
import jh.utils.HttpUtils;
import jh.view.MyListView;


public class CommunityActivity extends BaseActivity {


    private MyListView listView;
    private ListView listView1;
    private CommunityAdapter adapter;
    private List<CModel> datas = new ArrayList<>();
    private int page = 1;
    private int size = 10;
    private UserModel userModel;
    private LinearLayout rightItem;
    private ProgressBar progressBar;
    private SwipeRefreshLayout swipeRefresh;

    private String type;
    private String titleString;

    private int itemPosition;

    @Override
    public int getLayoutId() {
        return R.layout.acitvity_community;
    }

    @Override
    public void initData(Bundle savedInstanceState) {

        type = getIntent().getStringExtra("type");
        titleString = getIntent().getStringExtra("title");


        userModel = UserModel.getUserInfo(this);
        getData();
    }

    @Override
    public void initView() {

        backButton = find(R.id.back_buton);
        showBackButton();
        title = find(R.id.navigation_title);
        title.setText(titleString);


        progressBar = find(R.id.progressBar);

        if ("交流圈".equals(titleString)){
            rightItem = find(R.id.navigation_item);
            rightItem.setVisibility(View.VISIBLE);
            rightItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent = new Intent(CommunityActivity.this,PostActivity.class);
                    startActivityForResult(intent,1000);
                }
            });
        }

        listView = find(R.id.list_view);
        adapter = new CommunityAdapter(this,datas, new OnItemPictureClickListener() {
            @Override
            public void onItemPictureClick(int item,int position, String url, List<String> urlList, ImageView imageView) {
                try{
                itemPosition = item;
                Intent intent = new Intent(CommunityActivity.this, ImagePreviewActivity.class);
                intent.putStringArrayListExtra("imageList", (ArrayList<String>) urlList);
                intent.putExtra(P.START_ITEM_POSITION, itemPosition);
                intent.putExtra(P.START_IAMGE_POSITION, position);
                ActivityOptions compat = ActivityOptions.makeSceneTransitionAnimation(CommunityActivity.this, imageView, imageView.getTransitionName());
                startActivity(intent, compat.toBundle());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        listView.setAdapter(adapter);
        listView.setInteface(new MyListView.LoadListener() {
            @Override
            public void onLoad() {

                page ++;
                getData();
            }
        });

        swipeRefresh = findViewById(R.id.swipe_refresh);
        swipeRefresh.setColorSchemeResources(R.color.colorMain);
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
//                datas.clear();
                page = 1;
                listView.setEnabled(false);
                getData();
            }
        });
        swipeRefresh.setRefreshing(true);

        adapter.setaaListener(new CommunityAdapter.Listener(){

            @Override
            public void onClick(CModel a) {
                Intent mIntent = new Intent(CommunityActivity.this,PersonalCommunityActivity.class);
                mIntent.putExtra("CModel",a);
                startActivity(mIntent);
            }
        });
    }


    private void getData(){
        String url = "/api/communicationcircle/getCommunicationList";
        if ("POST".equals(type)){
            url = "/api/communicationcircle/mycomminucate";
        }else if("PRAISE".equals(type)){
            url = "/api/communicationcircle/mydz";
        }

        Map<String,String> map = new HashMap<>();
        map.put("page",page+"");
        map.put("size",size+"");
        if (userModel != null){
            map.put("uid",userModel.getUid()+"");
            map.put("loginToken",userModel.getLoginToken());
        }
        HttpUtils.POST(url, map, new HttpUtils.HttpResponse() {
            @Override
            public void callback(JSONObject object, String msg, Exception e) {
                progressBar.setVisibility(View.GONE);
                swipeRefresh.setVisibility(View.VISIBLE);
                swipeRefresh.setRefreshing(false);
                if (e == null){
                    if (msg == null){
                        try {
                            JSONArray jsonArray = object.getJSONArray("data");
                            GsonBuilder builder = new GsonBuilder();
                            Gson gson = builder.create();
                            List<CModel> list = gson.fromJson(jsonArray.toString(),new TypeToken<List<CModel>>(){}.getType());
                            if(page==1){datas.clear();}
                            datas.addAll(list);
                            adapter.notifyDataSetChanged();
                            listView.loadComplete();
                            listView.setEnabled(true);
                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1000){
//            datas.clear();  //清空datas放在添加datas数据之前，listveiw的bug
            page = 1;
            getData();
        }
    }
}
